/**
 * 工厂页直间达成率图表组件
 */
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import * as echarts from 'echarts'
import http from '@/axios/http'
import adaptivePx from '@/utils/adaptivePx'

const route = useRoute()
const factory = ref(route.query.factory)

const main = ref()
const directChart = ref()
const directDetail = ref()
let myChart = null

const date = new Date()
const lastYear = (date.getFullYear() - 1) + '年'
const thisTarget = String(date.getFullYear()).substring(2) + '年目标'
const thisYear = date.getFullYear() + '年'

async function getDirectChart() {
  await http.post('/factory/getDirectChart', {
    factory: factory.value
  }).then(res => {
    directChart.value = res.data
  }).catch(err => {
    console.log(err)
  })
}

async function getDirectDetail() {
  await http.post('/factory/getDirectDetail', {
    factory: factory.value
  }).then(res => {
    directDetail.value = res.data
  }).catch(err => {
    console.log(err)
  })
}

function init() {
  myChart = echarts.init(main.value, null, { renderer: 'svg'})

  let option = {
    title: {
      text: '直间达成率⭐',
      textStyle: {
        color: 'white',
        fontSize: adaptivePx(16),
        fontWeight: 'normal'
      },
      left: '2%',
      top: '2%'
    },
    color: ['#1e90ff', '#6a43ff', '#2fa8c3'],
    legend: {
      textStyle: {
        color: 'white',
        fontSize: adaptivePx(14),
        fontWeight: 'normal'
      },
      top: '2%',
      right: '2%',
      data: [lastYear, thisTarget, thisYear]
    },
    grid: {
      left: '3%',
      top: '27%',
      right: '5%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      boundaryGap: false,
      axisLabel: {
        color: 'white',
        fontSize: adaptivePx(12),
        fontWeight: 'normal'
      },
      data: directChart.value.month
    },
    yAxis: {
      max: function (value) {
        if (value.max > 100) {
          return 120
        } else {
          return 100
        }
      },
      min: 0,
      interval: 25,
      axisLabel: {
        color: 'white',
        formatter: '{value} %',
        fontSize: adaptivePx(12),
        fontWeight: 'normal'
      },
      axisLine: {
        lineStyle: {
          type: 'solid'
        },
        show: true
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#666'
        },
        show: true
      }
    },
    series: [
      {
        name: lastYear,
        type: 'line',
        data: directChart.value.lastDirectChart,
        emphasis: {
          scale: 3
        },
        markPoint: {
          symbol: directChart.value.lastDirectChart[directChart.value.lastDirectChart.length - 1] > 0 ? 'pin' : 'none',
          symbolSize: adaptivePx(55),
          symbolRotate: directChart.value.lastDirectChart[directChart.value.lastDirectChart.length - 1] <= directChart.value.thisDirectChart[directChart.value.thisDirectChart.length - 1] ? 180 : 0,
          label: {
            offset: [0, directChart.value.lastDirectChart[directChart.value.lastDirectChart.length - 1] <= directChart.value.thisDirectChart[directChart.value.thisDirectChart.length - 1] ? adaptivePx(10) : 0],
            color: 'white',
            fontSize: adaptivePx(12),
            fontWeight: 'normal'
          },
          data: [
            {
              name: 'Total',
              coord: [directChart.value.lastDirectChart.length - 1, directChart.value.lastDirectChart[directChart.value.lastDirectChart.length - 1]],
              value: directChart.value.lastDirectChart[directChart.value.lastDirectChart.length - 1] + '%'
            }
          ]
        },
      },
      {
        name: thisTarget,
        type: 'line',
        data: directChart.value.targetDirectChart,
        emphasis: {
          scale: 3
        }
      },
      {
        name: thisYear,
        type: 'line',
        data: directChart.value.thisDirectChart,
        areaStyle: {
          opacity: 0.2
        },
        emphasis: {
          scale: 3
        },
        markPoint: {
          symbol: directChart.value.thisDirectChart[directChart.value.thisDirectChart.length - 1] > 0 ? 'pin' : 'none',
          symbolSize: adaptivePx(55),
          symbolRotate: directChart.value.thisDirectChart[directChart.value.thisDirectChart.length - 1] < directChart.value.lastDirectChart[directChart.value.lastDirectChart.length - 1] ? 180 : 0,
          label: {
            offset: [0, directChart.value.thisDirectChart[directChart.value.thisDirectChart.length - 1] < directChart.value.lastDirectChart[directChart.value.lastDirectChart.length - 1] ? adaptivePx(10) : 0],
            color: 'white',
            fontSize: adaptivePx(12),
            fontWeight: 'normal'
          },
          data: [
            {
              name: 'Total',
              coord: [directChart.value.thisDirectChart.length - 1, directChart.value.thisDirectChart[directChart.value.thisDirectChart.length - 1]],
              value: directChart.value.thisDirectChart[directChart.value.thisDirectChart.length - 1] + '%'
            }
          ]
        },
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line',
        axis: 'x',
        lineStyle: {
          type: 'solid',
          color: '#ccc',
          width: 3
        }
      },
      textStyle: {
        color: 'black',
        fontSize: adaptivePx(14),
        fontWeight: 'normal'
      },
      backgroundColor: 'rgba(171, 182, 212, 0.9)',
      borderWidth: 0,
      position: function (point, params, dom, rect, size) {
        return [point[0] + adaptivePx(20), point[1] - size.contentSize[1] * 0.5]
      },
      formatter: function (params) {
        let year = (new Date()).getFullYear()
        let month = directDetail.value[params[0].name == 'Total' ? 'YY' : params[0].name]
        let content = ''

        let last = month.length - 1

        if (!month[last].this_rate && !month[last].last_rate && !month[last].target_rate) {
          return "暂无数据"
        }

        content += `
          <table style="text-align: center; font-weight: normal;">
            <thead>
              <tr>
                <th></th>
        `
        if (month[last].target_rate != '0%') {
          content += `
                <th>&nbsp;目标&nbsp;</th>
          `
        }
        if (month[last].this_rate != '0%') {
          content += `
                <th>&nbsp;${ year }年${ params[0].name === 'Total' ? '全年' : params[0].name + '月' }&nbsp;</th>
          `
        }
        if (month[last].last_rate != '0%') {
          content += `
                <th>&nbsp;${ year - 1 }年${ params[0].name === 'Total' ? '全年' : params[0].name + '月' }&nbsp;</th>
          `
        }
        if (month[last].this_rate != '0%' && month[last].last_rate != '0%') {
          content += `
                <th>&nbsp;VS${ String(year - 1).substring(2) }&nbsp;</th>
          `
        }
        content += `
              </tr>
            </thead>
            <tbody>
        `
        for (let i = 0; i < month.length; i++) {
          content += `
              <tr>
                <td style="text-align: left;">${ month[i].dept }</td>
          `
          if (month[last].target_rate != '0%') {
            content += `
                  <td>${ month[i].target_rate }</td>
            `
            
          }
          if (month[last].this_rate != '0%') {
            if (month[last].target_rate != '0%') {
              let diff = (month[i].this_rate == '\\' ? 0 : parseInt(month[i].this_rate)) - (month[i].target_rate == '\\' ? 0 : parseInt(month[i].target_rate))
              if (diff < 0) {
                content += `
                  <td style="color: red;">${ month[i].this_rate }</td>
                `
              } else {
                content += `
                  <td>${ month[i].this_rate }</td>
                `
              }
            } else {
              content += `
                  <td>${ month[i].this_rate }</td>
              `
            }
          }
          if (month[last].last_rate != '0%') {
            content += `
                <td>${ month[i].last_rate }</td>
            `
          }
          if (month[last].this_rate != '0%' && month[last].last_rate != '0%') {
            let diff = (month[i].this_rate == '\\' ? 0 : parseInt(month[i].this_rate)) - (month[i].last_rate == '\\' ? 0 : parseInt(month[i].last_rate))
            if (diff > 0) {
              content += `
                <td style="color: blue;">+${ diff }%</td>
              `
            } else {
              content += `
                <td style="color: red;">${ diff }%</td>
              `
            }
          }
        }
        content += `
              </tr>
            </tbody>
          </table>
        `

        return content
      }
    }
  }

  myChart.setOption(option)
}

function myChartResize() {
  if (myChart) {
    myChart.resize()
  }
}

onMounted(async () => {
  await getDirectChart()
  await getDirectDetail()
  init()
  
  window.addEventListener('resize', myChartResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', myChartResize)
})
</script>

<template>
  <div id="factory-direct-chart" ref="main"></div>
</template>

<style lang="scss" scoped>
#factory-direct-chart {
  width: 100%;
  height: 100%;
}
</style>